# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from typing import Optional

from cn.edu.cdu.argorithme.commons.list_node import ListNode


class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        dummy = ListNode(-1, head)
        prev = dummy
        while True:
            tail = prev
            for _ in range(k):
                tail = tail.next
                if tail is None:
                    return dummy.next

            curr = prev.next
            for _ in range(k - 1):
                _next = curr.next
                curr.next = _next.next
                _next.next = prev.next
                prev.next = _next
            prev = curr